﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Nexterday.Linq.Autocompiler
{
    public class ExpressionFlattener
    {

        public static Expression Flatten(Expression expression)
        {
            return Evaluator.PartialEval(
            expression,
            CanBeEvaluatedLocally);
        }
        static Func<Expression, bool> CanBeEvaluatedLocally
        {
            get
            {
                return expression =>
                    {


                        // don't evaluate parameters
                        if (expression.NodeType == ExpressionType.Parameter)
                            return false;

                        // can't evaluate queries
                        if (typeof(IQueryable).IsAssignableFrom(expression.Type))
                            return false;

                        
                        return true;
                    };
            }
        }

    }

}